import { NextRequest, NextResponse } from 'next/server';
import { initializeDatabase, getMessages } from '@/lib/database';
import { withCors } from '@/lib/cors';

// 初始化数据库
let dbInitialized = false;
async function ensureDatabaseInitialized() {
  if (!dbInitialized) {
    await initializeDatabase();
    dbInitialized = true;
  }
}

// GET /api/messages/[sessionId] - 获取会话的所有消息
async function handleGET(
  request: NextRequest,
  { params }: { params: { sessionId: string } }
) {
  try {
    await ensureDatabaseInitialized();

    const messages = await getMessages(params.sessionId);
    return NextResponse.json({ messages });
  } catch (error) {
    console.error('获取消息失败:', error);
    return NextResponse.json(
      { error: '获取消息失败' },
      { status: 500 }
    );
  }
}

// 导出带 CORS 支持的处理器
export const GET = withCors(handleGET);
